<script setup>

import {deleteSysFile, listSysFile} from "@/api/system/file_list";
import {computed, getCurrentInstance, ref, watch} from "vue";
import {enumToArray} from "@/utils/utils";
import {fileSourceList} from "@/enum/enum";
import SysFileForm from "@/components/Material/components/SysFileForm.vue";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['change'])
const props = defineProps({
  type: {
    type: Number,
    required: true,
    default: 1
  },
  cid: {
    type: Number,
  },
  mode: {
    type: String,
    default: 'page'
  },
  selectLimit: {
    type: Number,
    default: 1
  }
})
const queryForm = ref({
  type: null,
  cid: null,
  source: null,
  name: null,
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref();
const fileSourcesOptions = enumToArray(fileSourceList);
const total = ref(0);
const fileList = ref([]);
const ids = ref([]);
const selectedFiles = ref([]);
const disabled = ref(true);
const fileFormRef = ref();
const fileTypeColumn = computed(() => {
  switch (props.type) {
    case 1:
      return '图片';
    case 2:
      return '视频';
    case 3:
      return '文件';
  }
})
const tableRef = ref();

const getList = async () => {
  const {data} = await listSysFile(queryForm.value);
  total.value = data.total;
  fileList.value = data.list;
}

const handleQuery = () => {
  queryForm.value.pageNo = 1;
  getList();
}

const handleReset = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

const handleSelectionChange = (selection) => {
  if (props.mode === 'picker') {
    if (selection.length > props.selectLimit) {
      proxy.$modal.warningNotify(`最多只能选择${props.selectLimit}个文件`);
      return;
    }
    ids.value = selection.map(item => item.id);
    selectedFiles.value = selection;
    emit('change', selectedFiles.value);
  } else {
    ids.value = selection.map(item => item.id);
    selectedFiles.value = selection;
    disabled.value = !selection.length;
  }
}

const handleDelete = async (row) => {
  const fileId = row.id || ids.value;
  proxy.$modal.confirm(`确定删除选中文件吗？删除时本地存储文件也随之删除`).then(async () => {
    await deleteSysFile(fileId);
    proxy.$modal.okNotify('删除成功');
    await getList();
  })
}

const openFile = (row, type) => {
  const fileId = row?.id || ids.value;
  fileFormRef.value.open(fileId, type, props.type)
}

const removeSelectedFile = (file) => {
  if (props.mode === 'picker') {
    if (file === 'all') {
      selectedFiles.value = [];
      ids.value = [];
    } else {
      let fileIndex = selectedFiles.value.findIndex(item => item.id === file.id);
      if (fileIndex !== -1) {
        selectedFiles.value.splice(fileIndex, 1);
        ids.value = selectedFiles.value.map(item => item.id);
      }
    }
    emit('change', selectedFiles.value);
  }
}

watch(() => props.type, (newVal) => {
  if (newVal) {
    queryForm.value.type = newVal;
    getList();
  }
}, {immediate: true})

watch(() => props.cid, (newVal) => {
  // if (newVal != null) {
  queryForm.value.cid = newVal;
  getList();
  // }
}, {immediate: true})
getList();

defineExpose({
  removeSelectedFile
})
</script>

<template>
  <div v-bind="props">
    <div class="flex justify-between">
      <div class="flex mb-5">
        <upload
            v-if="type === 1"
            :data="{
              type:type,
              cid:cid==null?0:cid
            }"
            :type="type"
            :show-progress="true"
            @change="getList"
            class="mr-12px">
          <a-button type="primary" plain class="flex items-center"
                    v-hasPermission="['system:file:upload']">
            <icon icon="ep-upload" size="14px" color="unset" class="mr-1"/>
            上传文件
          </a-button>
        </upload>
        <upload
            v-if="type === 2 || type === 3"
            :data="{
              type:type,
              cid:cid==null?0:cid
            }"
            :type="type"
            :show-progress="true"
            @all-success="getList"
            class="mr-12px">
          <a-button type="primary" plain class="flex items-center"
                    v-hasPermission="['system:file:upload']">
            <icon icon="ep-upload" size="14px" color="unset" class="mr-1"/>
            上传文件
          </a-button>
        </upload>

        <a-button success plain class="flex items-center mr-2" :disabled="disabled"
                  @click="openFile(null,'move')" v-if="mode === 'page'" v-hasPermission="['system:file:move']">
          <icon icon="ep-edit" size="14px" color="unset" class="mr-1"/>
          移动
        </a-button>
        <a-button danger plain class="flex items-center" :disabled="disabled"
                  @click="handleDelete" v-if="mode === 'page'" v-hasPermission="['system:file:delete']">
          <icon icon="ep-delete" size="14px" color="unset" class="mr-1"/>
          删除
        </a-button>
      </div>
      <a-form label-width="80px" :model="queryForm" ref="queryFormRef" layout="inline" class="demo-form-inline">
        <a-form-item name="source">
          <a-select v-model:value="queryForm.source" placeholder="请选择文件来源">
            <a-select-option v-for="(item,index) in fileSourcesOptions" :key="index" :value="item.value"
                             :label="item.label">{{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item name="name">
          <a-input v-model:value="queryForm.name" placeholder="请输入文件名称"/>
        </a-form-item>
        <a-form-item>
          <a-space wrap>
            <a-button type="primary" @click="handleQuery" class="flex items-center mr-2">
              <icon icon="ep-search" size="14px" color="unset" class="mr-1"/>
            </a-button>
            <a-button plain @click="handleReset">
              <icon icon="ep-refresh" size="14px" color="unset" class="mr-1"/>
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <a-table
        ref="tableRef"
        :data-source="fileList"
        :border="true"
        size="large"
        class="container"
        :scroll="{ y: 550 }"
        :pagination="false"
        row-key="id"
        :row-selection="{
        selectedRowKeys: ids,
        onChange: (selectedRowKeys,selectedRows) => handleSelectionChange(selectedRows)
      }">
      <a-table-column type="selection" width="10px"/>
      <a-table-column data-index="uri" :title="fileTypeColumn" width="100" align="center">
        <template #default="{record}">
          <image-preview v-if="record.type === 1" :src="record.uri" width="60px" height="60px"/>
          <video-preview v-if="record.type === 2" :src="record.uri" width="60px" height="60px"/>
          <img v-if="record.type === 3" src="@/assets/images/file_thumb.png" width="60px" height="60px"/>
        </template>
      </a-table-column>
      <a-table-column data-index="name" :title="`${fileTypeColumn}名称`"/>
      <a-table-column data-index="createTime" title="上传时间"/>
      <a-table-column fixed="right" label="操作" width="200px">
        <template #default="{record}">
          <a-button class="ml-2" type="link" @click="openFile(record,'rename')"
                    v-hasPermission="['system:file:rename']">重命名
          </a-button>
          <a-button class="ml-2" type="link" danger @click="handleDelete(record)"
                    v-hasPermission="['system:file:delete']">
            删除
          </a-button>
        </template>
      </a-table-column>
    </a-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNo"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"/>

    <sys-file-form ref="fileFormRef" @success="getList"/>
  </div>
</template>

<style scoped lang="scss">
.container {
}
</style>
